package com.hx.impl;

import com.hx.dao.UserDao;
import com.hx.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class UserDaoImpl  implements UserDao {
    //注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int add(User user) {
        //插入数据库SQL
        String sql = "insert into user values(null,?,?,?,?)";
        //将user的属性值放在一个数组中
        Object[] args = {user.getUname(),user.getUpwd(),user.getUaddr(),user.getUtel()};
        //执行新加方法
        final int update = jdbcTemplate.update(sql, args);

        return update;
    }
    @Override
    public int update(User user){
        String sql = "update user set uname=?,upwd=?,uaddr=?,utel=? where id = ?";
        Object[] args ={user.getUname(),user.getUpwd(),user.getUaddr(),user.getUtel(),user.getId()};
        int update = jdbcTemplate.update(sql,args);
        return update;
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from user where id=?";
        final int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
        return 0;
    }

    @Override
    public int getAll() {
        String sql = "select * from user";
        final Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
        return integer;
    }

    @Override
    public User selectUserById(Integer id) {
        String sql = "select * from user where id=?";
        final User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
        return user;
    }

    @Override
    public List<User> findAllUser() {
        String sql = "select * from user";
        final List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return query;
    }

    @Override
    public int batchAddUser(List<Object[]> batchArgs) {
        String sql = "insert into user values(null,?,?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
        return 0;
    }

    @Override
    public void batchupdateUser(List<Object[]> batchArgs) {
        String sql = "update user set uname=?,upwd=?,uaddr=?,utel=? where id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);

    }

    @Override
    public void batchdelete(List<Object[]> batchArgs) {
        String sql = "delete from user where id=?";
        final int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    @Override
    public void updateMoreUser(List<Object[]> args) {
        String sql = "update user set uname ?, upwd=? , where id=?";
        jdbcTemplate.batchUpdate(sql,args);

    }


}
